import configparser
import sys
import os
current_file_path = os.path.abspath(__file__)
factory_root_parent_dir = os.path.dirname(os.path.dirname(current_file_path))
sys.path.insert(0, factory_root_parent_dir)

from flask import Flask, request, jsonify
from flask_socketio import SocketIO, emit
import threading
from flask_cors import CORS  # 允许跨域
from utils.randomUtils import generate_random_string
from managers.userManager import UserManager, ProjectManager
from db.userDBManager import UserDBManager

import agentscope 
config = configparser.ConfigParser()
config.read('config.ini')
openai_api_key = config['Global']['api_key']
OPENAI_CFG_DICT = {
    "config_name": "openai_cfg",    # 此配置的名称，必须保证唯一
    "model_type": "openai_chat",         # 模型类型
    "model_name": config['Global']['model'],  # 模型名称
    "api_key": openai_api_key,      # OpenAI API key. 如果没有设置，将使用环境变量中的 OPENAI_API_KEY

    "client_args": {
        "base_url": config['Global']['base_chat_url']
    },
}
agentscope.init(model_configs=[OPENAI_CFG_DICT])#, studio_url="http://0.0.0.0:5000")

# 创建主 Flask 应用
app = Flask(__name__)
socketio = SocketIO(app)
userDBManager = UserDBManager()
userManager = UserManager(userDBManager)
projectManager = ProjectManager(app)


CORS(app, resources={r"/api/*": {"origins": "*"}, r"/socket.io/*": {"origins": "*"}})

# 启动 Flask 服务和 SocketIO 实例
def start_socketio_instance(port, socketio):
    socketio.run(app, port=port)

@app.route('/api/login', methods=['POST'])
def login():
    data = request.get_json()
    userID = userDBManager.login(data['username'], data['password'])
    if userID is not None:
        if (userManager.getUser(userID)is None):
            userManager.addUser( userID )
        u = userDBManager.get_user_login_info(userID)
        return {'success':True, 'userID':userID, 'username':u['username'], 'message': 'Login successful'}
    else:
        return {'success':False, 'userID':None, 'username':None, 'message': 'Login failed'}

@app.route('/api/register', methods=['POST'])
def register():
    data = request.get_json()
    username = data.get('username')
    user_email = data.get('user_email')
    user_password = data.get('user_password')
    userID = userDBManager.register(username, user_email, user_password)
    if userID is not None:
        return {'success':True,'userID':userID,'username':username, 'message': 'Registration successful'}
    else:
        return {'success':False, 'userID':None, 'username':None, 'message': 'Registration failed'}

@app.route('/api/checkProjectRunning', methods=['POST'])
def checkProjectRunning():
    data = request.get_json()
    user_id = data.get('userID')
    project_id = data.get('projectID')
    user = userManager.getUser(user_id)
    if (user is None): return {'success':False, 'running':False}
    if (project_id not in user.getRunningProjects().keys()): return {'success':True, 'running':False}
    return {'success':True, 'running':True}

@app.route('/api/fetchUserEditingProjects', methods=['POST'])
def fetchUserEditingProjects():
    data = request.get_json()
    user_id = data.get('userID')
    projects = userManager.getUser(user_id).getEditingProjects()
    returnCode = []
    for k,v in projects.items():
        returnCode.append({'projectID':k, **v})
    print(returnCode)
    return jsonify({'success':True, 'projects':returnCode})

@app.route('/api/saveUserProject', methods=['POST'])
def saveUserProject():
    data = request.json
    userID = data.get('userID')
    projectID = data.get('projectID')
    projectContent = data.get('content')
    user = userManager.getUser(userID)
    if (user is None): return {'success':False, 'message':'User not found'}
    user.saveUserProject(projectID, projectContent)
    return {'success':True, 'message':'Project saved'}

@app.route('/api/getUserRunningToken', methods=['POST'])
def getUserRunningToken():
    data = request.json
    userID = data.get('userID')  
    if (userManager.getUser(userID) == None):
        return {'data':[]}
    user = userManager.getUser(userID)
    projects = user.getRunningProjects()
    returnCode = []
    for projectk, projectv in projects.items(): 
        for route in projectv.onlineRoutes.values():
            returnCode.append({'user_id':route['user_id'],'username':user.user_info['username'], 'project_id':route['project_id'], 'token':route['ws_token'] })
    return {'data':returnCode}
                    
# 创建一个动态 WebSocket 路由
@app.route('/api/createWS', methods=['POST'])
def create_websocket():
    data = request.json
    userID = data.get('userID')  
    projectID = data.get('currentProject')  
    if (userManager.getUser(userID) == None):
        return {'success':False, 'message': 'User not loged in!'}
    user = userManager.getUser(userID)
    user.stopProject(projectID)
    user.deployProject(projectID, userManager.getUser(userID).getEditingProject(projectID)['content'])
    
    return {'success':True, 'message': 'Created!'}, 200



# 启动 Flask 服务
if __name__ == '__main__':
    socketio.run(app, debug=True, port=5000)